package fun.yizhierha.operation.controller;

import fun.yizhierha.common.annotation.Log;
import fun.yizhierha.common.base.BaseErrDto;
import fun.yizhierha.common.exception.BadRequestException;
import fun.yizhierha.common.exception.BizCodeEnum;
import fun.yizhierha.common.utils.ValidUtils;
import fun.yizhierha.common.utils.*;
import fun.yizhierha.common.utils.file.FileUtil;
import fun.yizhierha.operation.domain.OraDatabase;
import fun.yizhierha.operation.domain.vo.CreateOraDatabaseVo;
import fun.yizhierha.operation.domain.vo.UpdateOraDatabaseVo;
import fun.yizhierha.operation.domain.vo.RetrieveOraDatabaseVo;

import fun.yizhierha.operation.service.OraDatabaseService;
import fun.yizhierha.operation.util.SqlUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.jsqlparser.schema.Database;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import lombok.RequiredArgsConstructor;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.Set;

/**
 * generated by EH-Admin
 *
 * @author xaopohi
 * @date Wed Dec 21 16:08:00 CST 2022
 **/
@Api(tags = "运维管理:部署管理")
@RestController
@RequestMapping("/api/operation/database")
@RequiredArgsConstructor
public class OraDatabaseController {

    private final OraDatabaseService oraDatabaseService;

    @ApiOperation("获取部署管理")
    @Log("获取部署管理")
    @GetMapping
    @PreAuthorize("@eh.check('operation:oraDatabase:list')")
    public R<PageUtils<OraDatabase>> list(RetrieveOraDatabaseVo retrieveOraDatabaseVo, Query.PageVo pageVo) {
        PageUtils<OraDatabase> res = oraDatabaseService.list(retrieveOraDatabaseVo, pageVo);
        return R.<PageUtils<OraDatabase>>ok().setData(res);
    }

    @ApiOperation("新增部署管理")
    @Log("新增部署管理")
    @PostMapping
    @PreAuthorize("@eh.check('operation:oraDatabase:add')")
    public R<List<BaseErrDto>> add(@Validated @RequestBody CreateOraDatabaseVo createOraDatabaseVo,
                                   BindingResult bindingResult) {
        List<BaseErrDto> errDtoList = ValidUtils.getBaseErrDtoByBindingRes(bindingResult);
        if (errDtoList.isEmpty()) {
            oraDatabaseService.save(createOraDatabaseVo);
            return R.ok();
        }
        return R.<List<BaseErrDto>>error(
                BizCodeEnum.Client_Error_CRUD.getCode(), BizCodeEnum.Client_Error_CRUD.getMsg()
        ).setData(errDtoList);
    }

    @ApiOperation("修改部署管理")
    @Log("修改部署管理")
    @PutMapping
    @PreAuthorize("@eh.check('operation:oraDatabase:edit')")
    public R<List<BaseErrDto>> edit(@Validated @RequestBody ValidList<UpdateOraDatabaseVo> updateOraDatabaseList,
                                    BindingResult bindingResult) {
        List<BaseErrDto> errDtoList = ValidUtils.getBaseErrDtoByBindingRes(updateOraDatabaseList, bindingResult);
        if (errDtoList.isEmpty()) {
            oraDatabaseService.edit(updateOraDatabaseList, errDtoList);
            if (errDtoList.isEmpty()) {
                return R.ok();
            } else {
                return R.<List<BaseErrDto>>error(
                        BizCodeEnum.Client_Error_CRUD.getCode(),
                        BizCodeEnum.Client_Error_CRUD.getMsg()
                ).setData(errDtoList);
            }
        }
        return R.<List<BaseErrDto>>error(
                BizCodeEnum.Client_Error_CRUD.getCode(),
                BizCodeEnum.Client_Error_CRUD.getMsg()
        ).setData(errDtoList);
    }

    @ApiOperation("删除部署管理")
    @Log("删除部署管理")
    @DeleteMapping
    @PreAuthorize("@eh.check('operation:oraDatabase:del')")
    public R del(@RequestBody Set<Long> ids) {
        oraDatabaseService.remove(ids);
        return R.ok();
    }

    @ApiOperation("导出数据")
    @Log("导出数据")
    @GetMapping("/download")
    @PreAuthorize("@eh.check('operation:oraDatabase:list')")
    public void download(HttpServletResponse response) {
        oraDatabaseService.download(response);
    }

    @Log("测试数据库链接")
    @ApiOperation(value = "测试数据库链接")
    @PostMapping("/testConnect/{dbId}")
    @PreAuthorize("@eh.check('operation:oraDatabase:testConnect')")
    public R<Boolean> testConnect(@PathVariable Long dbId) {
        return R.<Boolean>ok().setData(oraDatabaseService.testConnection(dbId));
    }

    @Log("执行SQL脚本")
    @ApiOperation(value = "执行SQL脚本")
    @PostMapping(value = "/upload/{dbId}")
    @PreAuthorize("@eh.check('operation:oraDatabase:add')")
    public R uploadDatabase(@RequestBody MultipartFile file, HttpServletRequest request,@PathVariable Long dbId) throws Exception {
        OraDatabase database = oraDatabaseService.getById(dbId);
        String fileName;
        if (database != null) {
            fileName = file.getOriginalFilename();
            File executeFile = new File(FileUtil.getFileDir() + fileName);
            FileUtil.del(executeFile);
            file.transferTo(executeFile);
            String result = SqlUtils.executeFile(database.getJdbcUrl(), database.getUserName(), database.getPwd(), executeFile);
            return R.ok().setData(result);
        } else {
            return R.error("数据库不存在!");
        }
    }
}